package com.example.aidlclient;

import androidx.appcompat.app.AppCompatActivity;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Binder;
import android.os.Bundle;
import android.os.IBinder;
import android.os.MemoryFile;
import android.os.ParcelFileDescriptor;
import android.os.RemoteException;
import android.util.Log;
import android.view.View;


import com.example.aidl.BookController;
import com.example.aidl.IBook;

import java.io.FileDescriptor;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Random;


public class MainActivity extends AppCompatActivity {
    String TAG = "AIDLService";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        bindService();
    }

    private void initView() {
        findViewById(R.id.bt_getList).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(bookController!=null){
                    try {
                        Log.d(TAG,"长度为="+bookController.getBookList().size());
                        List<IBook>  books =bookController.getBookList();
//                        for (IBook book:books ){
//                            Log.d(TAG,book.getName()+"  "+book.getPrice());
//                        }
                        for (int i=0;i<books.size();i++){
                            Log.d(TAG,books.get(i).getName()+"  "+books.get(i).getPrice());
                        }
                    } catch (RemoteException e) {
                        e.printStackTrace();
                    }
                }else {
                    Log.d(TAG,"未连接成功");
                }
            }
        });

      findViewById(R.id.bt_add_book).setOnClickListener(new View.OnClickListener() {
          @Override
          public void onClick(View v) {
              if(bookController!=null){
                  try {
                      bookController.addBookInOut(new IBook(new Random().nextInt(),"新书"));
                  } catch (RemoteException e) {
                      e.printStackTrace();
                  }
              }else {
                  Log.d(TAG,"未连接成功");
              }

          }
      });

        findViewById(R.id.bt_send_bitmap).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(bookController!=null){
                    try {

                        Bundle bundle = new Bundle();
                        BitMapIBinder.Stub stub = new BitMapIBinder.Stub() {

                            @Override
                            public Bitmap getBitmap() throws RemoteException {
                                Bitmap bitmap1 = null;
                                try {
                                    bitmap1 = BitmapFactory.decodeStream(getAssets().open("qmsht.jpg"));
                                } catch (IOException e) {

                                }
                                return bitmap1;
                            }

                            @Override
                            public byte[] getBytes() throws RemoteException {
                                return new byte[1024*1024];
                            }


                        };
                        bundle.putBinder("sjl",stub);
                        Log.d(TAG,"发送图片");
                        bookController.sendBitmap(bundle);
                    } catch (RemoteException e) {
                        e.printStackTrace();
                    }
                }else {
                    Log.d(TAG,"未连接成功");
                }

            }
        });

        findViewById(R.id.bt_send_file).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (bookController!=null){
                  byte[] data =  new byte[1024*1024*4+100];
                    for (int i = 0; i <data.length ; i++) {
                        data[i]= (byte) i;
                    }
                    try {
                        bookController.sendData(writeToMemoryFile(data));
                    } catch (RemoteException e) {
                        e.printStackTrace();
                    }
                }

            }
        });
    }

    //pfd = writeToMemoryFile(bytes);

    private ParcelFileDescriptor writeToMemoryFile(byte[] bytes) {
        Log.d(TAG,"tongfei writeToMemoryFile ");
        MemoryFile memoryFile = null;
        try {
            memoryFile = new MemoryFile("data", bytes.length);
            memoryFile.writeBytes(bytes, 0, 0, bytes.length);
            FileDescriptor fileDescriptor = (FileDescriptor) ReflectUtils.invoke("android.os.MemoryFile", memoryFile, "getFileDescriptor");
            // 需要反射调用
            Method getFileDescriptorMethod = memoryFile.getClass().getDeclaredMethod("getFileDescriptor");
            return ParcelFileDescriptor.dup(fileDescriptor);
          /*  if (getFileDescriptorMethod != null) {
                ReflectUtils.invokeMethod(memoryFile,memoryFile);
                //FileDescriptor fileDescriptor = (FileDescriptor) getFileDescriptorMethod.invoke(memoryFile);
                // 序列化，才可传送
                return ParcelFileDescriptor.dup(fileDescriptor);
            }*/
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (memoryFile != null) {
                memoryFile.close();
            }
        }
        return null;
    }

    BookController bookController;
    private void bindService() {
        Intent intent = new Intent();
        intent.setPackage("com.example.aidl");
        intent.setAction("com.example.aidl");
        bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE);
    }
    ServiceConnection serviceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            Log.d(TAG,"连接成功");
             bookController  = BookController.Stub.asInterface(service);
        }
        @Override
        public void onServiceDisconnected(ComponentName name) {
            Log.d(TAG,"未连接成功");
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbindService(serviceConnection);
    }



}
